// 引入状态码statusCode
const statusCode = require('./statusCode')

// 定义请求路径, BASEURL: 普通请求API; CBASEURL: 中台API,不使用中台可不引入CBASEURL
// 定义默认参数

/**
 * 发送请求
 * @params
 * method: <String> 请求方式: POST/GET
 * url: <String> 请求路径
 * data: <Object> 请求参数
 * ignoreToken: <Boolean> 是否忽略token验证
 * form: <Boolean> 是否使用formData请求
 */
function request(options) {
  const defaultOptions = {
    data: {},
    ignoreToken: false,
    form: false,
    userDefinedHeader: {}
  }
  let _options = Object.assign(defaultOptions, options)
  let {
    method,
    url,
    data,
    ignoreToken,
    form,
    userDefinedHeader
  } = _options
  // 设置请求头
  let header = {}
  if (form) {
    header = {
      'content-type': 'application/x-www-form-urlencoded',
    }
  } else {
    header = {
      'content-type': 'application/json; charset=utf-8', //自定义请求头信息
    }
  }
  if (JSON.stringify(userDefinedHeader) !== '{}') {
    header = {
      ...header,
      ...userDefinedHeader
    }
  }
  if (!ignoreToken) {
    let token = wx.getStorageSync('token') // 从全局变量中获取token
    let wxuuid = wx.getStorageSync('wxuuid') // 获取uuid
    header = Object.assign(header, {
      Authorization: token,
      "CTL-VERSION": wx.getAccountInfoSync()?.version || '2.6.0', //版本号
      "CTL-CLIENT": "WXAppLET", //客户端
      "CTL-DEVID": wxuuid || '', //设备id
      "CTL-CHANNEL": "NATURE", //渠道信息
      "CTL-APP": "AICOTTAGE" //指定产品
    })
    // header.Authorization = token
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url,
      data,
      header,
      method,
      timeout: 120000,
      success: (res) => {
        let {
          statusCode: code
        } = res
        if (code === statusCode.SUCCESS || code === statusCode.SUCCESS2) {
          resolve(res.data)
        } else if (code === statusCode.EXPIRE) {
          wx.removeStorageSync('token')
          wx.removeStorageSync('userInfo')
          reject(res)
        } else if (code === 400) {
          showToast(`${res.data.error_description||res.data.error||res.data.Message}`)
          reject(res)
        } else if (code === 502) {
          showToast(`服务器异常，请稍后重试`)
          reject(res)
        } else if (code === 500) {
          showToast(`服务器异常，请稍后重试`)
          reject(res)
        } else {
          reject(res)
        }
      },
      fail: (err) => {
        showToast(err.errMsg)
        reject(err)
      }
    })
  })
}

// 封装toast函数
function showToast(title, icon = 'none', duration = 2500, mask = false) {
  wx.showToast({
    title: title || '',
    icon,
    duration,
    mask
  });
}

function get(options) {
  return request({
    method: 'GET',
    ...options
  })
}

function post(options) {
  // url, data = {}, ignoreToken, form
  return request({
    method: 'POST',
    ...options
  })
}

module.exports = {
  request,
  get,
  post
}